package com.ziq.zcamp.post

import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.os.Bundle
import android.text.TextUtils
import android.view.GestureDetector
import android.view.MotionEvent
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import android.widget.Toast
import androidx.activity.viewModels
import androidx.core.view.isVisible
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.viewpager2.widget.ViewPager2
import com.amap.api.services.core.LatLonPoint
import com.blankj.utilcode.util.ScreenUtils
import com.facebook.imagepipeline.request.ImageRequest
import com.gmlive.camp.dialog.share.ShareDialog
import com.permissionx.guolindev.PermissionX
import com.zhpan.bannerview.BaseBannerAdapter
import com.zhpan.bannerview.BaseViewHolder
import com.ziq.base.base.BaseActivity
import com.ziq.base.extension.*
import com.ziq.base.utils.SystemBarUtil
import com.ziq.base.utils.permission.PermissionUtil
import com.ziq.zcamp.R
import com.ziq.zcamp.api.service.ServiceModule.Companion.onApiFail
import com.ziq.zcamp.bean.place.LocationInfo
import com.ziq.zcamp.bean.post.*
import com.ziq.zcamp.constant.FollowRelation
import com.ziq.zcamp.databinding.ActivityDynamicDetailBinding
import com.ziq.zcamp.dialog.AlertDialog
import com.ziq.zcamp.dialog.AllCommentListDialog
import com.ziq.zcamp.dialog.CommentInputDialog
import com.ziq.zcamp.dialog.share.ActionItem
import com.ziq.zcamp.life.CampLifeActivity
import com.ziq.zcamp.login.ActionAfterLogin
import com.ziq.zcamp.login.LoginActivity
import com.ziq.zcamp.manager.DataManager
import com.ziq.zcamp.manager.GlobalContextManager
import com.ziq.zcamp.manager.PostManager
import com.ziq.zcamp.manager.UserManager
import com.ziq.zcamp.mine.PersonalHomePageActivity
import com.ziq.zcamp.mine.PicturePreviewActivity
import com.ziq.zcamp.place.PlaceDetailActivity
import com.ziq.zcamp.topics.TopicsDetailsActivity
import com.ziq.zcamp.util.*
import com.ziq.zcamp.view.SafetySimpleDraweeView
import dagger.hilt.android.AndroidEntryPoint
import java.text.DecimalFormat
import kotlin.math.floor

//帖子详情
@AndroidEntryPoint
class DynamicDetailActivity : BaseActivity() {
    private val binding: ActivityDynamicDetailBinding by binding()

    val mViewModel: DynamicDetailViewModel by viewModels()
    val mCommentViewModel: CommentViewModel by viewModels()

    private var detailId = ""
    private var detailUid = 0
    var source = ""
    var allCommentAdapter: AllCommentAdapter? = null
    var currentBannerIndex = 0
    val imageList: MutableList<ImageInfo> = mutableListOf()
    var sourceDetail: PostingDetail? = null

    private var hasGrantPermission = false
    companion object {
        const val DETAIL_ID = "detail_id"
        const val DETAIL_UID = "detail_uid"
        const val SOURCE = "source"
        const val COMMENT_ITEM = "comment_item"
        const val POSTING_DETAIL = "posting_detail"
        fun open(context: Context, id: String, uid: Int, comment : CommentItem? = null, detail: PostingDetail? = null) {
            val intent = Intent(context, DynamicDetailActivity::class.java)
            intent.putExtra(DETAIL_ID, id)
            intent.putExtra(DETAIL_UID, uid)
            intent.putExtra(COMMENT_ITEM, comment)
            intent.putExtra(POSTING_DETAIL, detail)
            GlobalContextManager.startActivity(context, intent)
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        try {
            if (intent.hasExtra(DETAIL_ID) && intent.hasExtra(DETAIL_UID)) {
                detailId = intent.getStringExtra(DETAIL_ID) ?: ""
                detailUid = intent.getIntExtra(DETAIL_UID, 0)
            }
            if (intent.hasExtra(SOURCE)) {
                source = intent.getStringExtra(SOURCE) ?: ""
            }
            if (intent.hasExtra(COMMENT_ITEM)) {
                mCommentViewModel.targetCommentItem  = intent.getSerializableExtra(COMMENT_ITEM) as CommentItem?
            }
            if (intent.hasExtra(POSTING_DETAIL)) {
                sourceDetail = intent.getSerializableExtra(POSTING_DETAIL) as PostingDetail?
            }

            PostManager.postRecord(detailId, detailUid.toString())
        } catch (e: Exception) {
            println("$e")
        }
        SystemBarUtil.immerseStatusBar(this.window, statusBarIsLight = true)

        binding.root

        checkPermissionStatus()

        binding.back.click {
            finish()
        }
        binding.more.click {
            onShowMore()
        }

        binding.tvCampLifeBadge.click {
            CampLifeActivity.open(this,detailUid)
        }

        UserManager.instance.apply {
            if (isLogin.value == true) {
                if (getUid() == detailUid) {
                    binding.btnFollow.visibility = View.GONE
                }
            }
        }
        binding.btnFollow.click {
            LoginActivity.checkLogin(object : ActionAfterLogin {
                override fun action() {
                    UserManager.instance.apply {
                        if (isLogin.value == true) {
                            if (binding.btnFollow.isSelected) {
                                onUnFollow()
                            } else {
                                followUser(detailUid)
                            }
                        }
                    }
                }
            })
        }

        binding.llUserInfo.click {
            PersonalHomePageActivity.open(this, detailUid)
        }

        binding.banner.setAdapter(ImageAdapter())
        binding.banner.setAutoPlay(false)
        binding.banner.setCanLoop(false)
        binding.banner.setOffScreenPageLimit(5)
        binding.banner.setIndicatorVisibility(View.GONE)
        binding.banner.registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() {
            override fun onPageSelected(position: Int) {
                super.onPageSelected(position)
                currentBannerIndex = position
                updateBannerIndex(position)
            }
        })


        UserManager.instance.userFollowRelation.observe(this, Observer {
            it?.let {
                if (it.containsKey(detailUid)) {
                    when {
                        it[detailUid] == FollowRelation.mutual.value -> {
                            binding.btnFollow.isSelected = true
                            binding.tvFollow.setText(R.string.mutual_follow)
                            binding.tvFollow.setTextColor(Color.parseColor("#C5BFBB"))
                        }
                        it[detailUid] == FollowRelation.following.value -> {
                            binding.btnFollow.isSelected = true
                            binding.tvFollow.setText(R.string.followed)
                            binding.tvFollow.setTextColor(Color.parseColor("#C5BFBB"))
                        }
                        else -> {
                            binding.btnFollow.isSelected = false
                            binding.tvFollow.setText(R.string.follow)
                            binding.tvFollow.setTextColor(Color.parseColor("#FFFFFF"))
                        }
                    }
                }
            }
        })
        mViewModel.dimiss.observe(this, Observer {
            finish()
            overridePendingTransition(0, 0)
        })

        mViewModel.statusShow.observe(this, Observer {
            it?.let { data ->
                if(data.action != null){
                    binding.statusView.setStatus(it.status, updateActionBtn = { btn ->
                        btn.click {
                            data.action
                        }
                    })
                } else {
                    binding.statusView.setStatus(it.status)
                }
            }
        })
        mViewModel.postingDetail.observe(this, Observer {
            it?.let {
                mCommentViewModel.likeStatus.value = UserManager.PostingLikeStatus(it.post?.like_nums?:0, it.post?.is_like?:false)
                mCommentViewModel.commentCount.value = it.post?.comment_nums?:0
            }
        })
        mCommentViewModel.commentData.observe(this, Observer {
            updateComment(it)
        })
        mCommentViewModel.currentInput.observe(this, Observer {
            binding.commentAction.tvCommentActionInput.text = it
        })
        mCommentViewModel.commentCount.observe(this, Observer { count ->
            mViewModel.postingDetail.value?.let { detail ->
                detail.post?.comment_nums = count
                updateUI(detail)
            }
        })

        mCommentViewModel.likeStatus.observe(this, Observer { status ->
            mViewModel.postingDetail.value?.let { detail ->
                detail.post?.like_nums = status.num
                detail.post?.is_like = status.isLike
                updateUI(detail)
            }
        })



        UserManager.instance.postingLike.observe(this, Observer {
            mViewModel.postingDetail.value?.let {
                updateLikeUI(true, it)
            }
        })

        mCommentViewModel.initData(detailUid, detailId)
        mCommentViewModel.onRefreshComment()
        UserManager.instance.apply {
            if (isLogin.value == true) {
                getFollowRelation(detailUid)
            }
        }

        binding.root.post {
            if(mCommentViewModel.targetCommentItem != null){
                AllCommentListDialog(this, detailUid, detailId, "post").show()
            }
        }

        if(sourceDetail != null){
            updateUI(sourceDetail!!)
        } else {
            updateDetail()
        }

        PostManager.postEditSuccessId.observe(this, Observer {
            if(it != null && it == detailId){
                updateDetail()
            }
        })

        UserManager.instance.campCollect.observe(this, Observer {
            it?.let {
                val campId = mViewModel.postingDetail.value?.camp_info?.id?:0
                if(it.containsKey(campId)){
                    binding.llCamp.ivCollection.isSelected = it[campId] == 0
                }
            }
        })
    }

    private fun updateDetail(){
        launchWithTry (whenTry = {
            //解决刷新banner 不刷新问题，兼容了 评论导致闪烁问题
            imageList.clear()
            mViewModel.requestDetail(detailId, "$detailUid")
        })
    }

    override fun onPause() {
        super.onPause()
    }

    override fun onResume() {
        super.onResume()
        mViewModel.postingDetail.value?.let {
            updateLikeUI(true, it)
        }
    }

    private fun onUnFollow() {
        AlertDialog(this)
            .setTitle {
                it.append(GlobalContextManager.getString(R.string.are_you_sure_unfollow))
            }
            .setCancelButton(text = {it.append(GlobalContextManager.getString(R.string.cancel))}, action = {it.dismiss()})
            .setConfirmButton(text = {it.append(GlobalContextManager.getString(R.string.confirm))}, action = {
                it.dismiss()
                UserManager.instance.unfollowUser(detailUid)
            })
            .show()
    }

    fun updateBannerIndex(position: Int) {
        if (imageList.size <= 1) {
            binding.bannerIndex.visibility = View.GONE
        } else {
            binding.bannerIndex.visibility = View.VISIBLE
            binding.bannerIndex.text = "${position + 1}/${imageList.size}"
        }
    }

    @SuppressLint("SetTextI18n")
    private fun updateUI(postingDetail: PostingDetail) {

        ImageUtil.updateImageFromNetwork(binding.avator, postingDetail.user?.header_url?:"", ImageRequest.CacheChoice.DEFAULT)

        binding.name.text = postingDetail.user?.nick_name ?: ""
        binding.tvCampLifeBadge.setCampNum(postingDetail.user?.camping_count)
        binding.time.text = postingDetail.post?.publish_time?:""

        if(postingDetail.user?.ip_locate?.isNotEmpty() == true){
            binding.tvIp.text = "发布于${postingDetail.user?.ip_locate}"
        }

        var showLine = false
        if(postingDetail.post?.content?.isNotEmpty() == true){
            binding.detailContent.visibility = View.VISIBLE
            TopicsUtils.topicsSetColor(binding.detailContent,postingDetail.post?.content ?: "",postingDetail.post?.topicList?: emptyList(),
                click = {
                mViewModel.requestTopicsDetail(it.replace("#","")){ topics ->
                    if (topics.name.isNullOrEmpty()){
                        Toast.makeText(this@DynamicDetailActivity,"这个话题不见啦",Toast.LENGTH_SHORT).show()
                    }else{
                        TopicsDetailsActivity.open(this@DynamicDetailActivity,it,topics,"post_detail")
                    }
                }
            })
            showLine = true
        }
        if(postingDetail.post?.title?.isNotEmpty() == true){
            binding.detailTitle.visibility = View.VISIBLE
            binding.detailTitle.text = postingDetail.post?.title ?: ""
            showLine = true
        }

        val hasCampInfo = postingDetail.camp_info?.id != null && postingDetail.camp_info?.camp_name?.isNotEmpty() == true
        //营地信息优先
        val hasPoi = (!hasCampInfo) && (postingDetail.post?.location_addr?.isNotEmpty() == true)
        binding.llLocationInfo.visibility = View.GONE
        if (hasCampInfo) {
            binding.llLocationInfo.visibility = View.VISIBLE
            binding.llCamp.root.visibility = View.VISIBLE
            val imageInfo = postingDetail.camp_info?.images?.get(0)
            ImageUtil.updateImageFromNetwork(binding.llCamp.ivCampImage, imageInfo?.url?:"", ImageRequest.CacheChoice.DEFAULT)
            binding.llCamp.tvCampName.text = postingDetail.camp_info?.camp_name?: ""
            binding.llCamp.root.click {
                PlaceDetailActivity.open(this, postingDetail.camp_info?.id!!, postingDetail.camp_info?.camp_name?:"", "post_detail")
            }
            val campInfo = postingDetail.camp_info
            if ((campInfo?.camp_score?:0) > 0){
                binding.llCamp.rbCampScore.isVisible = true
                binding.llCamp.tvCampScore.isVisible = true
                binding.llCamp.rbCampScore.rating = roundDown(campInfo?.camp_score?:0).toFloat()
                binding.llCamp.tvCampScore.text =  DecimalFormat("0.0").format((campInfo?.camp_score?:0) / 10f)
            }else{
                binding.llCamp.rbCampScore.isVisible = false
                binding.llCamp.tvCampScore.isVisible = false
            }

            binding.llCamp.ivCollection.isSelected = campInfo?.is_collect?:false

            binding.llCamp.ivCollection.click {
                LoginActivity.checkLogin ( object : ActionAfterLogin {
                    override fun action() {
                        UserManager.instance.apply {
                            if(isLogin.value == true){
                                if(binding.llCamp.ivCollection.isSelected){
                                    collectCamp(campInfo?.id?:0, 1, onSuccess = {
                                        Toast.makeText(this@DynamicDetailActivity, "已取消收藏", Toast.LENGTH_SHORT).show()
                                    })
                                } else {
                                    collectCamp(campInfo?.id?:0, 0, onSuccess = {
                                        val msg = "收藏成功 可在“我的-收藏”中查看"
                                        Toast.makeText(GlobalContextManager.appContext!!, msg, Toast.LENGTH_SHORT).show()
                                    }, onFail = {
                                        UserManager.instance.updateCollectCamp(campInfo?.id?:0)
                                        Toast.makeText(this@DynamicDetailActivity,"收藏失败，请稍后再试",Toast.LENGTH_SHORT).show()
                                    })

                                }
                            }
                        }
                    }
                })
            }

            if (hasGrantPermission){
                binding.llCamp.tvCampDistance.isVisible = true
                MapUtil.getCurrentLocation(callback = {
                    showDistance(binding.llCamp.tvCampDistance,it.longitude,it.latitude,campInfo?.longitude,campInfo?.latitude)
                })

            }else{
                binding.llCamp.tvCampDistance.isVisible = false
            }

            binding.llCamp.llContainer.isVisible = binding.llCamp.rbCampScore.isVisible || binding.llCamp.tvCampScore.isVisible || binding.llCamp.tvCampDistance.isVisible

            showLine = true
        } else {
            binding.llCamp.root.visibility = View.GONE
        }

        if (hasPoi) {
            binding.llLocationInfo.visibility = View.VISIBLE
            binding.tvLocation.visibility = View.VISIBLE
            binding.tvLocation.text = postingDetail.post?.location_addr?: ""
            binding.tvLocation.click {
                if (postingDetail.post?.longitude?.isNotEmpty() == true && postingDetail.post?.latitude?.isNotEmpty() == true) {
                    PermissionUtil.requestLocationPermission(this, onGrant = {
                        MapActivity.open(this, LocationInfo().apply {
                            site = postingDetail.post?.location_addr
                            longitude = postingDetail.post?.longitude
                            latitude = postingDetail.post?.latitude
                        })
                    })
                }
            }
            showLine = true
        } else {
            binding.tvLocation.visibility = View.GONE
        }

        if ((postingDetail.post?.camping_start_time?:0) > 0) {
            binding.tvCampDay.text = "露营日：${TimeUtil.getCampDayTime((postingDetail?.post?.camping_start_time?:0) * 1000, (postingDetail?.post?.camping_end_time?:0) * 1000)}"
            binding.tvCampDay.visibility = View.VISIBLE
            showLine = true
        } else {
            binding.tvCampDay.visibility = View.GONE
        }



        if(!showLine){
            binding.line.visibility = View.GONE
        }


        if(imageList.isEmpty()){
            if(postingDetail.post?.images?.isNotEmpty() == true){
                imageList.clear()
                imageList.addAll(postingDetail.post?.images!!)
                val imageInfo = postingDetail.post?.images?.get(0)!!
                val params = binding.flBanner.layoutParams as ViewGroup.LayoutParams
                params.width = ScreenUtils.getScreenWidth()
                params.height = PictureUtil.calculatePostingDetailPictureViewHeight(
                    ScreenUtils.getScreenWidth(),
                    imageInfo.width,
                    imageInfo.height
                )
                binding.flBanner.layoutParams = params
                binding.flBanner.visibility = View.VISIBLE
                binding.banner.create(imageList)
                updateBannerIndex(currentBannerIndex)
            }else {
                binding.flBanner.visibility = View.GONE
            }
        }

        //评论
        if((postingDetail.post?.comment_nums?:0) > 0){
            binding.commentsTitle.text = GlobalContextManager.getString(R.string.all_comment, postingDetail.post?.comment_nums?:0)
            binding.moreComments.text = GlobalContextManager.getString(R.string.check_remain_comment, postingDetail.post?.comment_nums?:0)
            binding.moreComments.click {
                AllCommentListDialog(this, detailUid, detailId, "post").show()
            }
        }else {
            binding.commentsTitle.setText(R.string.no_comment)
        }

        binding.commentAction.llCommentActionPraise.click {
            LoginActivity.checkLogin( object : ActionAfterLogin {
                override fun action() {
                    if(this@DynamicDetailActivity.isFinishing){
                        return
                    }
                    //点赞 帖子
                    if(binding.commentAction.llCommentActionPraise.isSelected){
                        updateDataForUnLike()
                        UserManager.instance.unlikePosting(postingDetail.post?.post_id?:"", postingDetail.user?.uid?:0, postingDetail.post?.like_nums?:0, onFail = {
                            updateDataForLike()
                        })
                        startPraiseSvga("like_cancel.svga")
                    } else {
                        updateDataForLike()
                        UserManager.instance.likePosting(postingDetail.post?.post_id?:"", postingDetail.user?.uid?:0, postingDetail.post?.like_nums?:0, onFail = {
                            updateDataForUnLike()
                        })
                        startPraiseSvga("like_commit.svga")
                    }
                }
            })
        }



        binding.commentAction.llCommentActionAllComment.click {
            AllCommentListDialog(this, detailUid, detailId, "post").show()
        }

        binding.commentAction.tvCommentActionInput.click {
            LoginActivity.checkLogin( object : ActionAfterLogin {
                override fun action() {
                    if(this@DynamicDetailActivity.isFinishing){
                        return
                    }
                    CommentInputDialog(this@DynamicDetailActivity, mViewModel.postingDetail.value?.post?.post_id?:"", mViewModel.postingDetail.value?.user?.uid?:0, source = "post").show()
                }
            })
        }
        updateLikeUI(true, postingDetail)

        if((postingDetail.post?.comment_nums?:0) > 0){
            binding.commentAction.tvCommentActionAllCommentCount.text = "${postingDetail.post?.comment_nums}"
        }else {
            binding.commentAction.tvCommentActionAllCommentCount.text = GlobalContextManager.getString(R.string.comment)
        }
    }

    fun updateDataForLike(){
        mViewModel.postingDetail.value?.let {
            it.post?.let {
                val likeNum = it.like_nums?:0
                it.like_nums = likeNum + 1
                it.is_like = true
            }
            updateLikeUI(false, it)
        }
    }

    fun updateDataForUnLike(){
        mViewModel.postingDetail.value?.let {
            it.post?.let {
                val likeNum = it.like_nums?:0
                if(likeNum > 0 ){
                    it.like_nums = likeNum - 1
                }
                it.is_like = false
            }
            updateLikeUI(false, it)
        }
    }

    fun updateLikeUI(considerManager: Boolean, postingDetail: PostingDetail){
        if(considerManager && postingDetail.post?.post_id?.isNotEmpty() == true && UserManager.instance.postingLike.value?.contains(postingDetail.post?.post_id) == true){
            binding.commentAction.llCommentActionPraise.isSelected = UserManager.instance.postingLike.value!![postingDetail.post!!.post_id]!!.isLike
            postingDetail.post?.like_nums = UserManager.instance.postingLike.value!![postingDetail.post!!.post_id]!!.num
            if(postingDetail.post?.like_nums?:0 > 0){
                binding.commentAction.tvCommentActionPraiseCount.text = "${postingDetail.post?.like_nums}"
            } else {
                binding.commentAction.tvCommentActionPraiseCount.text = GlobalContextManager.getString(R.string.give_a_like)
            }
        }else {
            binding.commentAction.llCommentActionPraise.isSelected = postingDetail.post?.is_like?:false
            if(postingDetail.post?.like_nums?:0 > 0){
                binding.commentAction.tvCommentActionPraiseCount.text = "${postingDetail.post?.like_nums}"
            } else {
                binding.commentAction.tvCommentActionPraiseCount.text = GlobalContextManager.getString(R.string.give_a_like)
            }
        }

        if(!binding.commentAction.ivCommentActionPraise.isAnimating){
            binding.commentAction.ivCommentActionPraise.clearsAfterStop = false
            binding.commentAction.ivCommentActionPraise.loops = 1
            if(binding.commentAction.llCommentActionPraise.isSelected){
            } else {
            }
        }
    }

    fun startPraiseSvga(path:String){
        binding.commentAction.ivCommentActionPraise.clearsAfterStop = false
        binding.commentAction.ivCommentActionPraise.loops = 1
    }

    val limit = 5
    fun updateComment(comments :List<CommentItem>?) {
        binding.llComment.visibility = View.VISIBLE
        if (comments?.isNotEmpty() == true) {
            binding.llNoComment.visibility = View.GONE
            binding.llCommentList.visibility = View.VISIBLE
            if(allCommentAdapter == null){
                allCommentAdapter = AllCommentAdapter(this, mCommentViewModel, "post")
                allCommentAdapter?.setActionListener(object : AllCommentAdapter.ActionListener {
                    override fun onCommentUserInfoClick(item: CommentItem) {
                        PersonalHomePageActivity.open(this@DynamicDetailActivity, item.user_info?.uid?:0)
                    }

                    override fun onReplyCommentUserInfoClick(item: ReplyCommentItem) {
                        PersonalHomePageActivity.open(this@DynamicDetailActivity, item.reply_info?.uid?:0)
                    }

                    override fun onCommentItemClick(
                        item: CommentItem,
                        groupPosition: Int,
                        adapterPosition: Int
                    ) {
                        if(this@DynamicDetailActivity.isFinishing){
                            return
                        }
                        CommentInputDialog(this@DynamicDetailActivity, mViewModel.postingDetail.value?.post?.post_id?:"", mViewModel.postingDetail.value?.user?.uid?:0,
                            position = groupPosition, commentItem = item, source = "post").show()
                    }

                    override fun onReplyCommentItemClick(item: ReplyCommentItem, groupPosition: Int, adapterPosition:Int) {
                        if(this@DynamicDetailActivity.isFinishing){
                            return
                        }
                        CommentInputDialog(this@DynamicDetailActivity, mViewModel.postingDetail.value?.post?.post_id?:"", mViewModel.postingDetail.value?.user?.uid?:0,
                            position = groupPosition, replyCommentItem = item, source = "post").show()
                    }
                })
                binding.rvComment.layoutManager = LinearLayoutManager(this)
                binding.rvComment.adapter = allCommentAdapter
            }

            if(comments.size > limit){
                binding.moreComments.visibility = View.VISIBLE
                allCommentAdapter?.setData(comments.subList(0, limit))
            } else {
                binding.moreComments.visibility = View.GONE
                allCommentAdapter?.setData(comments)
            }
        } else {
            binding.llNoComment.visibility = View.VISIBLE
            binding.llCommentList.visibility = View.GONE
            binding.btnLeaveComment.click {
                LoginActivity.checkLogin(object : ActionAfterLogin {
                    override fun action() {
                        if(this@DynamicDetailActivity.isFinishing){
                            return
                        }
                        CommentInputDialog(this@DynamicDetailActivity, mViewModel.postingDetail.value?.post?.post_id?:"", mViewModel.postingDetail.value?.user?.uid?:0
                            , source = "post").show()
                    }
                })
            }
        }
    }

    private fun onShowMore() {
        if(mViewModel.postingDetail.value == null){
            return
        }
        val tools = mutableListOf<ActionItem>()
        if (detailUid == UserManager.instance.getUid() && detailUid != 0) {
            tools.add(
                ActionItem(
                    R.drawable.icon_share_delete,
                    GlobalContextManager.getString(R.string.publish_delete)
                )
            )
        } else {
            tools.add(
                ActionItem(
                    R.drawable.icon_share_report,
                    GlobalContextManager.getString(R.string.report)
                )
            )
        }
        if (UserManager.instance.isPostAdministration()){
            tools.add(
                ActionItem(
                    R.drawable.icon_share_post_remove,
                    GlobalContextManager.getString(R.string.all_move_administration)
                )
            )
        }
        ShareDialog(this, tools,ShareDialog.POST_DETAIL,ShareDialog.POST, desc = detailId)
            .setPostingData(mViewModel.postingDetail.value)
            .setActionCallback {
                when (it) {
                    GlobalContextManager.getString(R.string.publish_delete) -> {
                        onDeletePosting()
                    }
                    GlobalContextManager.getString(R.string.report) -> {
                        Toast.makeText(
                            this@DynamicDetailActivity,
                            GlobalContextManager.getString(R.string.report_success),
                            Toast.LENGTH_SHORT
                        ).show()
                    }
                    GlobalContextManager.getString(R.string.all_move_administration) -> {
                        onAdminRemovePost()
                    }
                }
            }
            .show()

    }

    fun onDeletePosting() {
        AlertDialog(this)
            .setTitle {
                it.append(GlobalContextManager.getString(R.string.publish_delete_confirm))
            }
            .setCancelButton(text = {it.append(GlobalContextManager.getString(R.string.cancel))}, action = {it.dismiss()})
            .setConfirmButton(text = {it.append(GlobalContextManager.getString(R.string.confirm))}, action = {
                it.dismiss()
                mViewModel.delDetail(detailId, "$detailUid",
                    onSuccess = {
                        DataManager.increasePostingListVersion()
                        val msg = GlobalContextManager.getString(R.string.delete_success)
                        Toast.makeText(this@DynamicDetailActivity, msg, Toast.LENGTH_SHORT).show()
                        finish()
                    }
                )
            })
            .show()
    }

    fun onAdminRemovePost() {
        AlertDialog(this)
            .setTitle {
                it.append(GlobalContextManager.getString(R.string.post_admin_remove))
            }
            .setCancelButton(text = {it.append(GlobalContextManager.getString(R.string.cancel))}, action = {it.dismiss()})
            .setConfirmButton(text = {it.append(GlobalContextManager.getString(R.string.confirm))}, action = {
                it.dismiss()
                UserManager.instance.adminRemovePost(detailId,detailUid,onSuccess = {
                    DataManager.increasePostingListVersion()
                    finish()
                }, onFail = { msg ->
                    onApiFail(msg)
                })
            })
            .show()
    }

    inner class ImageAdapter : BaseBannerAdapter<ImageInfo>() {

        override fun getLayoutId(viewType: Int): Int {
            return R.layout.item_image_banner
        }

        @SuppressLint("ClickableViewAccessibility")
        override fun bindData(
            holder: BaseViewHolder<ImageInfo>,
            data: ImageInfo,
            position: Int,
            pageSize: Int
        ) {
            val imageView = holder.findViewById<SafetySimpleDraweeView>(R.id.image)
            ImageUtil.updateImageFromNetwork(imageView, data.url?:"", ImageRequest.CacheChoice.DEFAULT)
            holder.itemView.setOnClickListener(null)
            val bannerGestureDetector = GestureDetector(holder.itemView.context, object : GestureDetector.SimpleOnGestureListener() {
                override fun onSingleTapConfirmed(e: MotionEvent): Boolean {
                    if (imageList.isNotEmpty()) {
                        val list = ArrayList<String>()
                        for (item in imageList) {
                            list.add(item.url ?: "")
                        }
                        PicturePreviewActivity.open(this@DynamicDetailActivity, list, position)
                    }
                    return true
                }

                override fun onDoubleTap(e: MotionEvent): Boolean {
                    LoginActivity.checkLogin(object : ActionAfterLogin {
                        override fun action() {
                            if(this@DynamicDetailActivity.isFinishing){
                                return
                            }
                            val postingDetail = mViewModel.postingDetail.value
                            //点赞 帖子
                            //播放svga动画
                            if(!binding.svga.isAnimating){
                                binding.svga.loops = 1
                            }

                            if(!binding.commentAction.llCommentActionPraise.isSelected){
                                startPraiseSvga("like_commit.svga")
                            }
                            if(postingDetail != null){
                                if(!binding.commentAction.llCommentActionPraise.isSelected){
                                    updateDataForLike()
                                    UserManager.instance.likePosting(postingDetail.post?.post_id?:"", postingDetail.user?.uid?:0, postingDetail.post?.like_nums?:0, onFail = {
                                        updateDataForUnLike()
                                    })
                                }
                            }
                        }
                    })
                    return true
                }
            })
            holder.itemView.setOnTouchListener { _, event ->
                return@setOnTouchListener bannerGestureDetector.onTouchEvent(event)
            }
        }

    }

    private fun checkPermissionStatus(){
        var result = true
        for(item in PermissionUtil.locationPermission){
            if(!PermissionX.isGranted(GlobalContextManager.appContext!!, item)){
                result = false
            }
        }
        hasGrantPermission = result
    }


    private fun roundDown(num : Int) : Double{
        val a = num /10.0
        return if (a - floor(a) >= 0.5){
            floor(a) +0.5
        }else{
            floor(a)
        }
    }

    @SuppressLint("SetTextI18n")
    private fun showDistance(view : TextView,lon :Double , lat : Double, longitude :String?, latitude :String?){
        if (0.0 == lon && 0.0 == lat){
            return
        }
        if (!TextUtils.isEmpty(longitude)
            &&!TextUtils.isEmpty(latitude)){
            val la = latitude?.toDouble()
            val lo = longitude?.toDouble()
            val start = LatLonPoint(lat,lon)
            val end = LatLonPoint(la!!,lo!!)
            MapUtil.calculateRouteDistanceAsyn(this,start,end){ item ->
                if(item != null){
                    val distance = item.distance
                    if(distance > 1000){
                        view.text = "${DecimalFormat("0.#").format(distance / 1000)}km"
                    } else {
                        view.text = "${distance.toInt()}m"
                    }
                    view.visibility = View.VISIBLE
                }
            }
        }
    }

}

